package com.colbby.datahouse.db;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class SqlObject {
	private StringBuilder sql = new StringBuilder();
	private List<Object> params = new ArrayList<Object>();

	public SqlObject append(String sqlpart) {
		sql.append(sqlpart);
		return this;
	}

	public SqlObject addParam(Object param) {
		params.add(param);
		return this;
	}

	public boolean isEmpty() {
		return sql.length() == 0;
	}
	
	public SqlObject merge(SqlObject s) {
		sql.append(s.sql);
		params.addAll(s.params);
		return this;
	}
	
	public String getSql() {
		return sql.toString();
	}

	public List<Object> getParams() {
		return params;
	}

	public int executeUpdate(Connection conn) throws SQLException {
		try (PreparedStatement ps = conn.prepareStatement(sql.toString())) {
			int i = 1;
			for (Object param : params) {
				ps.setObject(i, param);
				i++;
			}
			return ps.executeUpdate();
		}
	}
}